﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web;
using System.Security;
using System.Security.Cryptography;

namespace DAL
{
    public class WeChatHelper
    {
        SQLHelper SQLHelper = null;
        QXHelper QXHelper = null;
        public WeChatHelper()
        {
            SQLHelper = new SQLHelper();
            QXHelper = new QXHelper();
        }


        #region token 验证
        public bool verifytoken(string token, string echoStr, string signature, string timestamp, string nonce)
        {
            string[] ArrTmp = { token, timestamp, nonce };
            Array.Sort(ArrTmp);//字典排序
            string tmpStr = string.Join("", ArrTmp);

            //sha1 哈希加密
            SHA1 sha1 = new SHA1CryptoServiceProvider();
            byte[] bytes_in = Encoding.UTF8.GetBytes(tmpStr);
            byte[] bytes_out = sha1.ComputeHash(bytes_in);
            sha1.Dispose();
            var sb = new StringBuilder();
            foreach (byte b in bytes_out)
            {
                sb.Append(b.ToString("x2"));
            }
            //所有字符转为小写
            tmpStr = sb.ToString().ToLower();
            if (tmpStr == signature)//开发者获得加密后的字符串可与signature对比，标识该请求来源于微信。开发者通过检验signature对请求进行校验，若确认此次GET请求来自微信服务器，请原样返回echostr参数内容，则接入生效，否则接入失败
            {
                return true;
            }
            else
            {
                return false;
            }
        }
        #endregion

        #region unix时间转换为datetime
        /// <summary> 
        /// unix时间转换为datetime 
        /// </summary> 
        /// <param name="timeStamp"></param> 
        /// <returns></returns> 
        public DateTime UnixTimeToTime(string timeStamp)
        {
            DateTime dtStart = TimeZone.CurrentTimeZone.ToLocalTime(new DateTime(1970, 1, 1));
            long lTime = long.Parse(timeStamp + "0000000");
            TimeSpan toNow = new TimeSpan(lTime);
            return dtStart.Add(toNow);
        }
        #endregion
        #region datetime转换为unixtime
        /// <summary> 
        /// datetime转换为unixtime 
        /// </summary> 
        /// <param name="time"></param> 
        /// <returns></returns> 
        public int ConvertDateTimeInt(System.DateTime time)
        {
            System.DateTime startTime = TimeZone.CurrentTimeZone.ToLocalTime(new System.DateTime(1970, 1, 1));
            return (int)(time - startTime).TotalSeconds;
        }
        #endregion

        #region 回复文本消息
        /// <summary>
        /// 回复文本消息
        /// </summary>
        /// <param name="FromUserName">要回复的用户</param>
        /// <param name="ToUserName">本订阅号啦</param>
        /// <param name="Content">回复的消息内容（换行：在content中能够换行，微信客户端就支持换行显示）</param>
        /// <returns></returns>
        public string xmlText(string FromUserName, string ToUserName, string Content)
        {
            StringBuilder sb = new StringBuilder();
            sb.Append(@"<xml>");
            sb.AppendFormat(@"<ToUserName><![CDATA[{0}]]></ToUserName>", FromUserName);
            sb.AppendFormat(@"<FromUserName><![CDATA[{0}]]></FromUserName>", ToUserName);
            sb.AppendFormat(@"<CreateTime>{0}</CreateTime>", ConvertDateTimeInt(DateTime.Now));
            sb.Append(@"<MsgType><![CDATA[text]]></MsgType>");
            sb.AppendFormat(@"<Content><![CDATA[{0}]]></Content>", Content);
            sb.Append(@"</xml>");
            return sb.ToString();
        }
        #endregion
        #region 回复图文消息明细
        /// <summary>
        /// 回复图文消息明细
        /// </summary>
        /// <param name="Title">图文消息标题</param>
        /// <param name="Description">图文消息描述</param>
        /// <param name="PicUrl">图片链接，支持JPG、PNG格式，较好的效果为大图360*200，小图200*200</param>
        /// <param name="Url">点击图文消息跳转链接</param>
        /// <returns></returns>
        public string xmlItem(string Title, string Description, string PicUrl, string Url)
        {
            StringBuilder sb = new StringBuilder();
            sb.Append(@"<item>");
            sb.AppendFormat(@"<Title><![CDATA[{0}]]></Title>", Title);
            sb.AppendFormat(@"<Description><![CDATA[{0}]]></Description>", Description);
            sb.AppendFormat(@"<PicUrl><![CDATA[{0}]]></PicUrl>", PicUrl);
            sb.AppendFormat(@"<Url><![CDATA[{0}]]></Url>", Url);
            sb.Append(@"</item>");
            return sb.ToString();
        }
        #endregion
        #region 回复图文消息
        /// <summary>
        /// 回复图文消息
        /// </summary>
        /// <param name="FromUserName">要回复的用户</param>
        /// <param name="ToUserName">本订阅号啦</param>
        /// <param name="ArticleCount">图文消息个数，限制为8条以内</param>
        /// <param name="Articles">多条图文消息信息，默认第一个item为大图,注意，如果图文数超过8，则将会无响应</param>
        /// <returns></returns>
        public string xmlNews(string FromUserName, string ToUserName, string ArticleCount, string Articles)
        {
            StringBuilder sb = new StringBuilder();
            sb.Append(@"<xml>");
            sb.AppendFormat(@"<ToUserName><![CDATA[{0}]]></ToUserName>", FromUserName);
            sb.AppendFormat(@"<FromUserName><![CDATA[{0}]]></FromUserName>", ToUserName);
            sb.AppendFormat(@"<CreateTime>{0}</CreateTime>", ConvertDateTimeInt(DateTime.Now));
            sb.Append(@"<MsgType><![CDATA[news]]></MsgType>");
            sb.AppendFormat(@"<ArticleCount>{0}</ArticleCount>", ArticleCount);
            sb.AppendFormat(@"<Articles>{0}</Articles>", Articles);
            sb.Append(@"</xml>");
            return sb.ToString();
        }
        #endregion
        #region 回复图片消息
        /// <summary>
        /// 回复图片消息
        /// </summary>
        /// <param name="FromUserName">要回复的用户</param>
        /// <param name="ToUserName">本订阅号啦</param>
        /// <param name="MediaId">通过素材管理中的接口上传多媒体文件，得到的id。</param>
        /// <returns></returns>
        public string xmlImage(string FromUserName, string ToUserName, string MediaId)
        {
            StringBuilder sb = new StringBuilder();
            sb.Append(@"<xml>");
            sb.AppendFormat(@"<ToUserName><![CDATA[{0}]]></ToUserName>", FromUserName);
            sb.AppendFormat(@"<FromUserName><![CDATA[{0}]]></FromUserName>", ToUserName);
            sb.AppendFormat(@"<CreateTime>{0}</CreateTime>", ConvertDateTimeInt(DateTime.Now));
            sb.Append(@"<MsgType><![CDATA[Image]]></MsgType>");
            sb.AppendFormat(@"<Image><MediaId><![CDATA[{0}]]></MediaId></Image>", MediaId);
            sb.Append(@"</xml>");
            return sb.ToString();
        }
        #endregion
        #region 回复视频消息
        /// <summary>
        /// 回复视频消息
        /// </summary>
        /// <param name="FromUserName">要回复的用户</param>
        /// <param name="ToUserName">本订阅号啦</param>
        /// <param name="MediaId">通过素材管理中的接口上传多媒体文件，得到的id</param>
        /// <param name="Title">视频消息的标题</param>
        /// <param name="Description">视频消息的描述</param>
        /// <returns></returns>
        public string xmlVideo(string FromUserName, string ToUserName, string MediaId, string Title, string Description)
        {
            StringBuilder sb = new StringBuilder();
            sb.Append(@"<xml>");
            sb.AppendFormat(@"<ToUserName><![CDATA[{0}]]></ToUserName>", FromUserName);
            sb.AppendFormat(@"<FromUserName><![CDATA[{0}]]></FromUserName>", ToUserName);
            sb.AppendFormat(@"<CreateTime>{0}</CreateTime>", ConvertDateTimeInt(DateTime.Now));
            sb.Append(@"<MsgType><![CDATA[video]]></MsgType>");
            sb.Append(@"<Video>");
            sb.AppendFormat(@"<MediaId><![CDATA[{0}]]></MediaId>", MediaId);
            sb.AppendFormat(@"<Title><![CDATA[{0}]]></Title>", Title);
            sb.AppendFormat(@"<Description><![CDATA[{0}]]></Description>", Description);
            sb.Append(@"</Video>");
            sb.Append(@"</xml>");
            return sb.ToString();
        }
        #endregion
        #region 回复音乐消息
        /// <summary>
        /// 回复音乐消息
        /// </summary>
        /// <param name="FromUserName">要回复的用户</param>
        /// <param name="ToUserName">本订阅号啦</param>
        /// <param name="Title">音乐标题</param>
        /// <param name="Description">音乐描述</param>
        /// <param name="MusicURL">音乐链接</param>
        /// <param name="HQMusicUrl">高质量音乐链接，WIFI环境优先使用该链接播放音乐</param>
        /// <param name="ThumbMediaId">缩略图的媒体id，通过素材管理中的接口上传多媒体文件，得到的id</param>
        /// <returns></returns>
        public string xmlMusic(string FromUserName, string ToUserName, string Title, string Description, string MusicURL, string HQMusicUrl, string ThumbMediaId)
        {
            StringBuilder sb = new StringBuilder();
            sb.Append(@"<xml>");
            sb.AppendFormat(@"<ToUserName><![CDATA[{0}]]></ToUserName>", FromUserName);
            sb.AppendFormat(@"<FromUserName><![CDATA[{0}]]></FromUserName>", ToUserName);
            sb.AppendFormat(@"<CreateTime>{0}</CreateTime>", ConvertDateTimeInt(DateTime.Now));
            sb.Append(@"<MsgType><![CDATA[video]]></MsgType>");
            sb.Append(@"<Music>");
            sb.AppendFormat(@"<Title><![CDATA[{0}]]></Title>", Title);
            sb.AppendFormat(@"<Description><![CDATA[{0}]]></Description>", Description);
            sb.AppendFormat(@"<MusicUrl><![CDATA[{0}]]></MusicUrl>", MusicURL);
            sb.AppendFormat(@"<HQMusicUrl><![CDATA[{0}]]></HQMusicUrl>", HQMusicUrl);
            sb.AppendFormat(@"<ThumbMediaId><![CDATA[{0}]]></ThumbMediaId>", ThumbMediaId);
            sb.Append(@"</Music>");
            sb.Append(@"</xml>");
            return sb.ToString();
        }
        #endregion
        #region 回复语音消息
        /// <summary>
        /// 回复语音消息
        /// </summary>
        /// <param name="FromUserName">要回复的用户</param>
        /// <param name="ToUserName">本订阅号啦</param>
        /// <param name="MediaId">通过素材管理中的接口上传多媒体文件，得到的id</param>
        /// <returns></returns>
        public string xmlVoice(string FromUserName, string ToUserName, string MediaId)
        {
            StringBuilder sb = new StringBuilder();
            sb.Append(@"<xml>");
            sb.AppendFormat(@"<ToUserName><![CDATA[{0}]]></ToUserName>", FromUserName);
            sb.AppendFormat(@"<FromUserName><![CDATA[{0}]]></FromUserName>", ToUserName);
            sb.AppendFormat(@"<CreateTime>{0}</CreateTime>", ConvertDateTimeInt(DateTime.Now));
            sb.Append(@"<MsgType><![CDATA[video]]></MsgType>");
            sb.Append(@"<Voice>");
            sb.AppendFormat(@"<MediaId><![CDATA[{0}]]></MediaId>", MediaId);
            sb.Append(@"</Voice>");
            sb.Append(@"</xml>");
            return sb.ToString();
        }
        #endregion


    }
}
